<?php defined('BASEPATH') or exit('Fuck You !');

class Cuiqg {

	private $CI;
	function __construct() {
		$this->CI =& get_instance();
	}

	function curlRequest($url, $param = array(), $type = 'post') {

		if($type == 'get') {
			$url .= '?'.http_build_query($param);
		}

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		// curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		if($type == 'post') {
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
		}
		$response = curl_exec($ch);
		curl_close($ch);

		return $response;
	}

	public function getAuthorCode() {

		try {

			$url = config_item('author_url');
			$param = array(
				'client_id' 	=> config_item('api_key'),
				'response_type'	=> 'code',
				'redirect_uri'	=> base_url('oauth_redirect/baidu'),
				'state'			=> 'cuiqg_ac',
				'display'		=> 'page',
				'force_login'	=> 0,
				'confirm_login'	=> 1,
				);
			return $url .'?'.http_build_query($param);
		}catch(Exception $e) {
			throw $e->getMessage();
		}
	}

	public function getAccessToken($code = '') {

		try {

			$url = config_item('token_url');
			$param = array(
				'grant_type'	=> 'authorization_code',
				'code' 			=> $code,
				'client_id'		=> config_item('api_key'),
				'client_secret'	=> config_item('secret_key'),
				'redirect_uri'	=> base_url('oauth_redirect/baidu'),
				);
			return $this->curlRequest($url, $param, 'get');

		}catch(Exception $e) {

			throw $e->getMessage();
		}
	}
	public function isJson($param = '')
	{
		json_decode($param);
		if(json_last_error() == JSON_ERROR_NONE)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public function doCache($key = '', $val = '' , $expires_in = 2700) {

		$this->CI->load->driver('cache');
		if($key && $val)
		{
			return $this->CI->cache->file->save($key, $val, $expires_in);
		}
		elseif($key)
		{
			return $this->CI->cache->file->get($key);
		}
	}

	public function getAudio($text = '', $token = '',$lang = 'zh') {

		$url = config_item('text2audio');

		$param = array(
			'tex' 	=> $text,
			'lan'	=> $lang,
			'tok'	=> $token,
			'ctp'	=> 1,
			'cuid'	=> $this->CI->input->ip_address(),
			'spd'	=> 5,
			'pit'	=> 5,
			'vol'	=> 7,
			'per'	=> 0,
			);

		$tmpData = $this->curlRequest($url, $param);
		if($this->isJson($tmpData))
		{
		 	$tmpStr = json_decode($tmpData, true);

		 	return array('status' => 'failed', 'message' => $tmpStr['err_msg']);
		}
		else
		{
			if(!file_exists("tmp")) {
				@mkdir("tmp", 0777, true);
			}

			@file_put_contents("tmp/temp.mp3", $tmpData);

			return array('status' => 'success', 'message' => 'success', 'results' => base_url("/tmp/temp.mp3"));
		}
	}
}